/**
 * Orthanc DICOM 实例发现工具
 * 用于自动发现和获取Orthanc中可用的DICOM实例
 */
import { orthancService } from '@/services/orthanc.service'
import type { DicomInstancePath } from '@/config/orthanc.config'

export interface DiscoveredInstance {
  studyInstanceUID: string
  seriesInstanceUID: string
  sopInstanceUID: string
  studyDescription?: string
  seriesDescription?: string
  modality?: string
  patientName?: string
  patientID?: string
}

/**
 * 发现Orthanc中的第一个可用DICOM实例
 */
export async function discoverFirstAvailableInstance(): Promise<DicomInstancePath | null> {
  try {
    console.log('🔍 正在发现Orthanc中的可用DICOM实例...')
    
    // 1. 获取研究列表
    const studies = await orthancService.getStudies()
    if (studies.length === 0) {
      console.log('❌ Orthanc中没有任何研究')
      return null
    }
    
    console.log(`📚 找到 ${studies.length} 个研究`)
    
    // 2. 获取第一个研究的系列
    const firstStudy = studies[0]
    const studyUID = firstStudy['0020000D']?.Value?.[0]
    
    if (!studyUID) {
      console.error('❌ 无法获取研究UID')
      return null
    }
    
    console.log(`📖 检查研究: ${studyUID}`)
    
    const series = await orthancService.getSeries(studyUID)
    if (series.length === 0) {
      console.log('❌ 研究中没有系列')
      return null
    }
    
    console.log(`📄 找到 ${series.length} 个系列`)
    
    // 3. 获取第一个系列的实例
    const firstSeries = series[0]
    const seriesUID = firstSeries['0020000E']?.Value?.[0]
    
    if (!seriesUID) {
      console.error('❌ 无法获取系列UID')
      return null
    }
    
    console.log(`📋 检查系列: ${seriesUID}`)
    
    const instances = await orthancService.getInstances(studyUID, seriesUID)
    if (instances.length === 0) {
      console.log('❌ 系列中没有实例')
      return null
    }
    
    console.log(`🖼️ 找到 ${instances.length} 个实例`)
    
    // 4. 获取第一个实例
    const firstInstance = instances[0]
    const instanceUID = firstInstance['00080018']?.Value?.[0]
    
    if (!instanceUID) {
      console.error('❌ 无法获取实例UID')
      return null
    }
    
    const discoveredInstance: DicomInstancePath = {
      studyInstanceUID: studyUID,
      seriesInstanceUID: seriesUID,
      sopInstanceUID: instanceUID,
      frameNumber: 1
    }
    
    console.log('✅ 发现可用实例:', discoveredInstance)
    return discoveredInstance
    
  } catch (error) {
    console.error('❌ 发现DICOM实例失败:', error)
    return null
  }
}

/**
 * 获取Orthanc中所有可用的DICOM实例摘要
 */
export async function getAllAvailableInstances(): Promise<DiscoveredInstance[]> {
  const instances: DiscoveredInstance[] = []
  
  try {
    console.log('🔍 正在获取所有可用DICOM实例...')
    
    const studies = await orthancService.getStudies()
    
    for (const study of studies) {
      const studyUID = study['0020000D']?.Value?.[0]
      if (!studyUID) continue
      
      try {
        const series = await orthancService.getSeries(studyUID)
        
        for (const seriesItem of series) {
          const seriesUID = seriesItem['0020000E']?.Value?.[0]
          if (!seriesUID) continue
          
          try {
            const instanceList = await orthancService.getInstances(studyUID, seriesUID)
            
            for (const instance of instanceList) {
              const instanceUID = instance['00080018']?.Value?.[0]
              if (!instanceUID) continue
              
              instances.push({
                studyInstanceUID: studyUID,
                seriesInstanceUID: seriesUID,
                sopInstanceUID: instanceUID,
                studyDescription: study['00081030']?.Value?.[0],
                seriesDescription: seriesItem['0008103E']?.Value?.[0],
                modality: seriesItem['00080060']?.Value?.[0],
                patientName: study['00100010']?.Value?.[0]?.Alphabetic,
                patientID: study['00100020']?.Value?.[0]
              })
            }
          } catch (error) {
            console.warn(`⚠️ 获取实例列表失败 (Series: ${seriesUID}):`, error)
          }
        }
      } catch (error) {
        console.warn(`⚠️ 获取系列列表失败 (Study: ${studyUID}):`, error)
      }
    }
    
    console.log(`✅ 总共发现 ${instances.length} 个DICOM实例`)
    return instances
    
  } catch (error) {
    console.error('❌ 获取所有DICOM实例失败:', error)
    return instances
  }
}

/**
 * 在浏览器控制台中显示可用实例
 */
export async function showAvailableInstances(): Promise<void> {
  console.log('📋 正在列出所有可用的DICOM实例...')
  
  const instances = await getAllAvailableInstances()
  
  if (instances.length === 0) {
    console.log('❌ 没有找到任何DICOM实例')
    console.log('💡 请确保:')
    console.log('   1. Orthanc服务器正在运行')
    console.log('   2. 已上传DICOM文件到Orthanc')
    console.log('   3. DICOM-Web插件已启用')
    return
  }
  
  console.log(`📊 找到 ${instances.length} 个可用实例:`)
  console.log('=' .repeat(80))
  
  instances.forEach((instance, index) => {
    console.log(`${index + 1}. 患者: ${instance.patientName || 'Unknown'} (${instance.patientID || 'N/A'})`)
    console.log(`   研究: ${instance.studyDescription || 'No Description'}`)
    console.log(`   系列: ${instance.seriesDescription || 'No Description'} (${instance.modality || 'Unknown'})`)
    console.log(`   Study UID: ${instance.studyInstanceUID}`)
    console.log(`   Series UID: ${instance.seriesInstanceUID}`)
    console.log(`   Instance UID: ${instance.sopInstanceUID}`)
    console.log('-'.repeat(40))
  })
  
  if (instances.length > 0) {
    const first = instances[0]
    console.log('💡 要使用第一个实例，请在配置文件中更新:')
    console.log(`export const exampleDicomInstance: DicomInstancePath = {`)
    console.log(`  studyInstanceUID: '${first.studyInstanceUID}',`)
    console.log(`  seriesInstanceUID: '${first.seriesInstanceUID}',`)
    console.log(`  sopInstanceUID: '${first.sopInstanceUID}',`)
    console.log(`  frameNumber: 1`)
    console.log(`}`)
  }
}

// 在浏览器控制台中暴露工具函数
if (typeof window !== 'undefined') {
  (window as any).discoverFirstAvailableInstance = discoverFirstAvailableInstance
  (window as any).getAllAvailableInstances = getAllAvailableInstances
  (window as any).showAvailableInstances = showAvailableInstances
}


